var isImageUpdaterLoaded = false;
var windowScrollTop;
var lastPage = null;
var currpage = null;

$(document).ready(function() {
	loadAjaxEntry();
	$(".s_ajax_entry.default").click();
	reloadListener();
});

function reloadListener() {
	onSizeChenge($(window).width());
	loadWindowChenge();
	$('.ui.checkbox').checkbox();
	$('.ui.radio.checkbox').checkbox();
	$(".s_modal_close").click(function() {
		$(".s_modal").modal("close");
	});
	bindTextraw();
}

function loadWindowChenge() {
	$(window).resize(function() {
		onSizeChenge($(window).width());
	});
}

function setCheckbox(name, head) {
	$("#" + head + name).click();
}

function setRadiobox(json, head) {
	if (json == "1")
		$("#" + head + "true").click();
	else
		$("#" + head + "false").click();
}

// TODO 这样写没啥大碍，但是不是异步，以后若有时间应当重写这里，改为异步请求.但就实际项目来说，服务器位于内网，很小可能出现延迟几十秒的问题。
function loadAjaxEntry() {
	$(".s_ajax_entry").click(
			function(e) {
				if ($(this).hasClass("disabled"))
					return;
				if ($(this).hasClass("s_ajax_entry_enabled"))
					return;
				$(".s_ajax_entry").removeClass("active").removeClass(
						"s_ajax_entry_enabled");
				if ($(this).attr("bind") != null) {
					console.log("nuk");
					$("." + $(this).attr("bind")).addClass("active").addClass(
							"s_ajax_entry_enabled")
				}
				;
				$(this).addClass("active").addClass("s_ajax_entry_enabled");
				$("#" + $(this).attr("targetid")).load($(this).attr("url"));
				loadPage($(this).attr("url"));
				setting_card = $(this).attr("target");
				if ($(this).attr("scroll") != "false") {
					window.scrollTo(0, 0);
				}
			});
}
function loadAnotherPagePassEntry(entryid,url){
	var entry = $("#"+entryid);
	$(".s_ajax_entry").removeClass("active").removeClass(
			"s_ajax_entry_enabled");
	if (entry.attr("bind") != null) {
		console.log("nuk");
		$("." + entry.attr("bind")).addClass("active").addClass(
				"s_ajax_entry_enabled")
	}
	;
	entry.addClass("active").addClass("s_ajax_entry_enabled");
	$("#" + entry.attr("targetid")).load(dealURL(url));
	loadPage(url);
	setting_card = entry.attr("target");
	if (entry.attr("scroll") != "false") {
		window.scrollTo(0, 0);
	}
}

function showCommonMessage(id, level, mess, time) {
	$("#" + id).attr("class", "ui message").addClass(level).html(mess);
}

function showMessage(id, code, mess) {
	var messagediv = $("#" + id);
	messagediv.removeClass("hidden");
	if (code == 0) {
		messagediv.removeClass("error");
		messagediv.addClass("success");
	} else {
		messagediv.removeClass("success");
		messagediv.addClass("error");
	}
	messagediv.html(mess);
}

function bindAjaxForm(s, onSuccess, onError, dimmerid) {
	s.ajaxForm({
		url : s.attr("url"),
		dataType : 'json',
		type : "post",
		beforeSubmit : function() {
			$("#" + dimmerid).addClass("active");
		},
		success : onSuccess,
		error : onError,
		complete : function(data) {
			s.val("");
			window.scrollTo(0, 0);
			$("#" + dimmerid).removeClass("active");
		}
	});
}

function submitBlobFile(data, post_url, onError, onSuccess) {
	var formData = new FormData();
	formData.append("file", data, "head.png");
	$.ajax({
		url : post_url,
		type : 'post',
		processData : false,
		contentType : false,
		data : formData,
		dataType : 'json',
		success : onSuccess,
		error : onError
	});
}

function ajaxRequest(formdata, url, onSuccess, onError, dimmerid) {
	$.ajax({
		url : url,
		dataType : 'json',
		type : "post",
		data : formdata,
		processData : false,
		beforeSubmit : function() {
			$("#" + dimmerid).addClass("active");
		},
		success : onSuccess,
		error : onError,
		complete : function(data) {
			$("#" + dimmerid).removeClass("active");
		}
	});
}

function searchInForm(element) {
	var s_url = element.attr("url");
	var target = $("#" + element.attr("target"));
	var s_data = "&" + target.attr("name") + "=" + target.val();
	$.ajax({
		url : s_url,
		dataType : "json",
		data : s_data,
		type : "POST",
		beforeSubmit : function() {
			$("#searchload").addClass("active");
		},
		success : function(data) {
			try {
				dealSearchResult(data["code"], data["message"], data);
			} catch (ex) {
				dealSearchResult(-99, data, data);
			}
		},
		error : function(data) {
			dealSearchResult(-101, data, data);
		},
		complete : function(data) {
			$("searchload").removeClass("active");
		}
	});
}

function writeErrorMessage(message) {
	$(".ui.error.message").html(message);
	$('.ajaxform').addClass("error");
}

function onSizeChenge(size) {
	if (size < 767) {
		s_g_loadPhoneMode();
		$(".s_shrink").hide();
		$(".s_menunentry").show();
		$(".s_removecolumn_phone").removeClass("column");
		$(".s_removegird_phone").removeClass("grid");
		$(".s_phone_twelve_to_sixteen").removeClass("twelve").removeClass(
				"wide");
		$(".s_phone_twelve_to_sixteen").addClass("sixteen").addClass("wide");
	} else {
		$(".s_shrink").show();
		$(".s_menunentry").hide();
		$(".s_removecolumn_phone").addClass("column");
		$(".s_removegird_phone").addClass("grid");
		$(".s_removeattached_pc").removeClass("attached");
		$(".s_phone_twelve_to_sixteen").removeClass("sixteen").removeClass(
				"wide");
		$(".s_phone_twelve_to_sixteen").addClass("twelve").addClass("wide");
	}
	if (size < 990) {
		$(".s_tablet_shrink").hide();
		$(".s_tablet_menunentry").show();
		$(".s_twelve_to_sixteen").removeClass("twelve").removeClass("wide");
		$(".s_twelve_to_sixteen").addClass("sixteen").addClass("wide");
		$(".s_removeattached_pc").addClass("attached");
	} else {
		s_g_loadTabletMode();
		$(".s_tablet_shrink").show();
		$(".s_tablet_menunentry").hide();
		$(".s_twelve_to_sixteen").removeClass("sixteen").removeClass("wide");
		$(".s_twelve_to_sixteen").addClass("twelve").addClass("wide");
		$(".s_removeattached_pc").removeClass("attached");
	}
	if (typeof (onChengeMode) === 'function') {
		onChengeMode(size < 767);
	}
}

function getHomeURL(uid) {
	return "index.php?mod=home&childmod=zone&uid=" + uid;
}

function gender_to_string(gender) {
	return gender == 1 ? "男" : "女";
}

function user_type_to_string(user_type) {
	if (user_type == 1) {
		return "家长";
	}
	if (user_type == 2) {
		return "教职工";
	}
	return "学生";
}

function dataURLtoBlob(dataurl) {
	var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(
			n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([ u8arr ], {
		type : mime
	});
}

function checkImageUpdaterScript() {
	if (!isImageUpdaterLoaded) {
		console.log("未加载ImageUpdaterScript");
		$.getScript('assets/script/stu_image_updater.js', function() {
			if (typeof (eval("onImageUpdaterScriptLoad"))) {
				onImageUpdaterScriptLoad();
			}
			console.log("成功加载ImageUpdaterScript");
		});
		return;
	}
	if (typeof (eval("onImageUpdaterScriptLoad"))) {
		onImageUpdaterScriptLoad();
	}
}

function checkBigFileUpdaterScript() {
	if (!isImageUpdaterLoaded) {
		console.log("未加载BigFileUpdater");
		$.getScript('assets/script/stu_big_file_updater.js', function() {
	
			if (typeof (eval("onBigFileUpdaterScriptLoad"))) {
				onBigFileUpdaterScriptLoad();
			}
			console.log("成功加载BigFileUpdater");
		});
	
		return;
	}
	if (typeof (eval("onBigFileUpdaterScriptLoad"))) {
		onBigFileUpdaterScriptLoad();
	}
}


function inDiv(div, x, y) {
	var y1 = div.offset().top;
	var y2 = y1 + div.height();
	var x1 = div.offset().left;
	var x2 = x1 + div.width();
	return !(x < x1 || x > x2 || y < y1 || y > y2);
}

function bindTextraw() {
	$(".s_flexible_textraw.two_ten").focus(function() {
		$(this).attr("rows", "10");
	});
	$(".s_flexible_textraw.two_ten").blur(function() {
		$(this).attr("rows", "2");
	});
}

function dealURL(url) {
	return url.replace(RegExp('&amp;', "g"), '&');
}

function getIndex(str, ca, num) {
	counts = str.split(ca);
	if (counts.length - 1 <= num)
		return str.length;
	i = 0;
	nowIndex = 0;
	while (i <= num - 1) {
		nowIndex += counts[i].length;
		nowIndex += ca.length;
		i++;
	}
	return nowIndex - ca.length;
}

function updateScroll() {
	windowScrollTop = $(window).scrollTop()
}

function reloadScroll() {
	window.scroll(0, windowScrollTop);
}

function　loadPage(url){
	lastPage = currpage;
	currpage = url;
}

function getLastPage(){
	return lastPage;
}

function s_g_loadTabletMode() {
	$(".s_a_tablet_drop").append($(".s_top_item"));
}
function s_g_loadPhoneMode() {
	$(".s_a_phone_drop").append($(".s_top_item"));
}

function Base64() {
	/*--------------------- 
	作者：fjb2080 
	来源：CSDN 
	原文：https://blog.csdn.net/fjb2080/article/details/81009210 
	版权声明：本文为博主原创文章，转载请附上博文链接！*/
    // private property
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
 
    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }
 
    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }
 
    // private method for UTF-8 encoding
    _utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
 
        }
        return utftext;
    }
 
    // private method for UTF-8 decoding
    _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}